package com.muyi.base.config.jwt;

import com.alibaba.fastjson.JSONObject;
import com.muyi.base.model.User;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: Administrator
 * @Date: 2018/11/29 14 41
 * @Description:
 */
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtService {
    private static final Logger logger = LoggerFactory.getLogger(JwtService.class);

    private long expire;
    private String secret;
    private String header;

    /**
     * 生成token
     * @param user
     * @return
     */
    public String generateToken(User user){
        Date nowDate = new Date();

        Date expireDate = new Date(nowDate.getTime() + expire * 1000);
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(JSONObject.toJSONString(user))
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }

    /**
     * 获取claim
     * @param token
     * @return
     */
    public Claims getClaimByToken(String token){
        try{
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        }catch (Exception e){
            logger.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * 得到user
     * @param claims
     * @return
     */
    public User getUser(Claims claims){
        return JSONObject.parseObject(claims.getSubject(), User.class);
    }

    public boolean isTokenExpired(Date expireation){
        return expireation.before(new Date());
    }

    public static Logger getLogger() {
        return logger;
    }

    public long getExpire() {
        return expire;
    }

    public void setExpire(long expire) {
        this.expire = expire;
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public String getHeader() {
        return header;
    }

    public void setHeader(String header) {
        this.header = header;
    }

    public static void main(String[] agrs) {
        JwtService jwtService = new JwtService();
        jwtService.setExpire(604800);
        jwtService.setSecret("f4e2e52034348f86b67cde581c0f9eb5");
        jwtService.setHeader("token");
        User user = new User();
        user.setUserId("9527");
        user.setName("aaaa");
        user.setPasswd("000000");
        String token = jwtService.generateToken(user);
        System.out.println(token);

        User user1 = JSONObject.parseObject(jwtService.getClaimByToken(token).getSubject(), User.class);
        System.out.println(user1);
    }
}
